<template>
  <div class="approve-flow-item">
    <el-icon class="delete" color="red" v-if="isLast" @click="deletehandle"><CircleCloseFilled /></el-icon>
    <div style="white-space: nowrap">
      <div class="node-name">
        {{ nodeInfo.nodeName }}
      </div>
      <div class="node-type">{{ dicFormatter(options.nodeTypeEnum, nodeInfo.nodeType) }}</div>
    </div>

    <div style="display: flex;flex-wrap: wrap;">
      <div v-for="(value, key) in nodeInfo.nodeContent?.formContent" style="display: flex;align-items: center;margin-bottom: 6px;">
        <div class="approver">
          {{ value }}
        </div>
        <el-icon class="plus" color="#BFBFBF" size="22px">
          <Plus/>
        </el-icon>
      </div>
      <el-popover :visible="visible" placement="bottom" :width="400" trigger="manual">
        <template v-slot:reference>
          <div class="add-approve-user" @click="openAddApproveUser">
            <el-icon color="#BFBFBF" size="24px">
              <Plus/>
            </el-icon>
          </div>
        </template>
        <div class="org-popover-select" @mouseleave="mouseout">
          <el-input v-if="nodeInfo.nodeType == options.nodeTypeEnum[0].value" suffix-icon="Search" v-model="searchVal" @input="searchChange"/>
          <el-input v-else suffix-icon="Search" v-model="searchVal" @input="userListSearchChange"/>
          <div class="tree" v-if="searchVal">
            <el-tree ref="orgSelectTreeRef" v-model="selectedKeys" :props="personTreeProps" :data="userList"
                     filterable show-checkbox @check-change="treeCheckChange" check-strictly multiple :default-checked-keys="defaultOrg"
                     node-key="organizationId"/>
          </div>
          <div class="tree" v-else>
            <el-tree v-if="nodeInfo.nodeType == options.nodeTypeEnum[0].value" ref="orgSelectTreeRef" v-model="selectedKeys" :props="orgTreeProps"
                     @check-change="treeCheckChange" filterable show-checkbox check-strictly multiple :filter-node-method="filterNodeMethod" :default-checked-keys="defaultOrg"
                     node-key="organizationId" :data="tree"/>
            <el-tree v-else ref="orgSelectTreeRef" v-model="selectedKeys" :props="personTreeProps" :filter-node-method="filterNodeMethod"
                     @check-change="treeCheckChange" filterable show-checkbox check-strictly multiple lazy :load="loadNode" :default-checked-keys="defaultOrg"
                     node-key="organizationId"/>
          </div>
          <div class="selected-num">
            <div class="sum">
              已选<span>{{ total }}</span>
            </div>
            <div>
              <el-button size="small" @click="closePopover">
                取消
              </el-button>
              <el-button type="primary" size="small" @click="handleConfirm">
                确定
              </el-button>
            </div>
          </div>
        </div>
      </el-popover>
    </div>

  </div>
</template>

<script>
import {dicFormatter} from "@/views/construction/project-application/projectUtil";
import OrgPopoverSelect from "@/views/construction/project-application/componens/OrgPopoverSelect";
import store from "@/store";
import {getUserInfo} from "@/api/eqpt/houseManger";

export default {
  name: "ApproveFlowItem",
  components: {OrgPopoverSelect},
  props: {
    index: {
      type: Number
    },
    isLast: {
      type: Boolean
    },
    nodeInfo: {
      type: Object,
      default: () => ({})
    },
  },
  inject: ["options"],
  computed: {
    defaultOrg () {
      if (this.nodeInfo.nodeContent?.formContent) {
        return Object.keys(this.nodeInfo.nodeContent.formContent)
      } else {}
      return []
    }
  },
  data() {
    return {
      dicFormatter,
      searchVal: undefined,
      searchInterval: undefined,

      total: 0,
      visible: false,
      selectedKeys: [],
      tree: [],
      userList: [],
      orgTreeProps: {
        label: 'organizationName',
        isLeaf: 'leaf',
        disabled: (data, node) => {
          return false
        }
      },
      personTreeProps: {
        label: 'organizationName',
        isLeaf: 'leaf',
        disabled: (data, node) => {
          return data.data?.organId
        }
      }
    }
  },
  mounted() {
    const tree = store.getters['user/getOrganTree']
    this.tree = tree
  },
  methods: {
    mouseout() {
      this.visible = false
    },
    deletehandle() {
      this.$emit('ondelete', this.index)
    },
    searchChange() {
      let val = this.searchVal || ''
      let searchVal = val.trim()
      if (this.searchInterval) {
        clearInterval(this.searchInterval)
      }
      this.searchInterval = setTimeout(() => {
        this.$refs.orgSelectTreeRef.filter(searchVal)
      }, 300)
    },
    async userListSearchChange() {
      if (this.searchInterval) {
        clearInterval(this.searchInterval)
      }
      let searchVal = this.searchVal.trim()
      if (!this.searchVal || !this.searchVal.trim()) {
        this.userList = []
        return
      }
      this.searchInterval = setTimeout(async() => {
        let res = await getUserInfo({})
        let perList = res.data.map(item => ({organizationId: item.userId, organizationName: item.name, leaf: true}))
        this.userList = perList.filter(item => item.organizationName.includes(searchVal))
      }, 300)
    },
    filterNodeMethod(searchVal, data, node) {
      return data.organizationName.includes(searchVal)
    },
    async loadNode(node, resolve) {
      if (node.level === 0) {
        const tree = store.getters['user/getOrganTree']
        resolve(tree)
      } else {
        if (node.data.children && node.data.children.length) {
          resolve(node.data.children)
        } else {
          let res = await getUserInfo({})
          let perList = res.data.map(item => ({organizationId: item.userId, organizationName: item.name, leaf: true}))
          resolve(perList)
        }
      }
    },
    treeCheckChange() {
      let checkedNodes = this.$refs.orgSelectTreeRef.getCheckedNodes()
      this.total = checkedNodes.length
    },
    openAddApproveUser() {
      this.$emit('onclose', this.index)
      this.visible = true
      let that = this
      let formContent = that.nodeInfo.nodeContent?.formContent
      let selectedKeys = formContent ? Object.keys(formContent) : []
      that.open({
        selectedKeys: selectedKeys,
        resolve: (checkedNodes) => {
          that.nodeInfo.nodeContent.formContent =
            checkedNodes.reduce((obj, item) => {
              obj[item.organizationId] = item.organizationName
              return obj
            }, {})
        }
      })
    },
    closePopover(index) {
      if (index !== this.index) {
        this.visible = false
      }
    },
    open({resolve}) {
      this.resolve = resolve
      this.visible = true
    },
    handleConfirm() {
      let checkedNodes = this.$refs.orgSelectTreeRef.getCheckedNodes()
      this.resolve(checkedNodes)
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>
.approve-flow-item {
  display: flex;
  position: relative;
  margin-bottom: 20px;

  .node-name {
    margin-right: 60px;
  }

  .node-type {
    margin-top: 5px;
    color: #a8a8a8;
    margin-right: 60px;
  }

  .approver {
    height: 40px;
    line-height: 40px;
    border-radius: 4px;
    padding: 0 5px;
    border: 1px solid #BFBFBF;
  }

  .plus {
    margin: 0 10px;
    font-weight: normal;
  }

  .add-approve-user {
    cursor: pointer;
    width: 42px;
    height: 42px;
    border-radius: 4px;
    border: 1px solid #BFBFBF;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
  }

}

.org-popover-select {
  display: flex;
  flex-direction: column;
  height: 300px;
  background: white;
  overflow: hidden;

  .tree {
    flex: 1;
    overflow: auto;
    padding: 10px 0;

  }

  .selected-num {
    border-top: 1px solid #F2F2F2;
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .sum span {
      color: #3393D9;
      margin-left: 5px;
      font-size: 18px;
    }
  }

  ::v-deep .is-disabled {
    display: none !important;
  }
}
.delete {
  cursor: pointer;
  position: absolute;
  left: -45px;
  top: 3px;
}
</style>
